package com.luo.demo.oidc.combo.controller;

import com.luo.demo.oidc.combo.dto.ThirdLoginDto;
import com.luo.demo.oidc.combo.service.PhoneSmsCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 集成三方登录 - controller
 *
 * @author luohq
 * @version 1.0.0
 * @date 2022-02-14 14:52
 */
@Controller
@RequestMapping("/combo")
@Slf4j
public class ComboLoginController {

    /**
     * SpringSecurity OAuth2 Client配置信息
     */
    @Resource
    private OAuth2ClientProperties oAuth2ClientProperties;

    @Resource
    private PhoneSmsCodeService phoneSmscodeService;

    @GetMapping("/login")
    public String login(Model model) {
        //设置model属性，用于登录页渲染展示第三方登录信息
        model.addAttribute("thirdLoginDtoList", this.extractThirdLoginDtoList());
        return "/login_combo";
    }

    @PostMapping("/sendSmsCode")
    @ResponseBody
    public String sendSmsCode(@RequestParam String phoneNo) {
        log.info("send smsCode, param: phoneNo={}", phoneNo);
        //发送验证码
        this.phoneSmscodeService.sendSmsCode(phoneNo);
        return "{'code': 100}";
    }

    /**
     * 提取第三方登录信息列表
     *
     * @return 第三方登录信息列表
     */
    private List<ThirdLoginDto> extractThirdLoginDtoList() {
        //获取OAuth2 Client注册信息
        Map<String, OAuth2ClientProperties.Registration> regId2DetailMap = oAuth2ClientProperties.getRegistration();
        //转换OAuth2 Client信息为三方登录信息
        return regId2DetailMap.keySet().stream()
                .map(regId -> {
                    OAuth2ClientProperties.Registration registration = regId2DetailMap.get(regId);
                    String curProviderId = StringUtils.hasText(registration.getProvider()) ? registration.getProvider() : regId;
                    return ThirdLoginDto.builder()
                            .providerId(curProviderId)
                            .loginUri(OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/" + curProviderId)
                            .loginIcon("/img/" + curProviderId + ".png")
                            .build();
                }).collect(Collectors.toList());
    }


}


